/**
 * 
 */
package com.rinvay.network.access;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.rinvay.network.http.conn.HttpConnection;

/**
 * @author rinvay
 * @date 2012-12-23 下午11:28:52
 */
public class NetworkDataLoader {
	
	private static ThreadPoolExecutor threadPool;

	/**
	 * 延迟初始化，同时，静态变量声明跟随app，线程池关闭后便不可用，须再次初始化。
	 */
	private static synchronized void initialize() {
		if (threadPool != null) {
			return;
		}

		// 一旦线程数大于核心池大小且处于闲置状态,会被立即回收掉
		threadPool = new ThreadPoolExecutor(Runtime.getRuntime()
				.availableProcessors() + 1, Runtime.getRuntime()
				.availableProcessors() + 1, 0L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>());
		// 设置保护策略;当队列任务已经满了,或者任务提交到一个已经关闭的executor,则丢弃该任务;<br>
		// 默认的保护策略是AbortPolicy,会抛出RejectedExecutionException
		threadPool
				.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
	}

	public static void shutdown() {
		if (threadPool != null) {
			threadPool.shutdownNow();
			threadPool = null;
		}
	}

	/**
	 * 退出
	 * 
	 * @throws InterruptedException
	 */
	public static void waitTerminationAndExit() throws InterruptedException {
		if (threadPool != null) {
			if (!threadPool.isShutdown()) {
				threadPool.shutdownNow();
			}
			threadPool.awaitTermination(3, TimeUnit.SECONDS);
			threadPool = null;
		}
	}

	
	
	public static void poolExcute(HttpConnection conn) {
		if (threadPool == null || threadPool.isShutdown()) {
			threadPool = null;
			initialize();
		}
		threadPool.execute(conn);
		
	}
	
	
	public static void excute(HttpConnection conn) {
		new Thread(conn).start();
	}
}
